- code
import React, { useState } from 'react';
import Image from 'next/image';
function ImageSlider() {
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const images = [
'圖片1',
'圖片2',
'圖片3',
'圖片4',
'圖片5'
];
//以下這兩個函數處理切換到下一張和上一張圖片的邏輯
const handleNextImage = () => {
setCurrentImageIndex((prevIndex) => (prevIndex + 1) % images.length);
};
const handlePrevImage = () => {
setCurrentImageIndex((prevIndex) => (prevIndex - 1 + images.length) % images.length);
};
return (
<div>
<h1>Image Slider</h1>
<div className="image-container">
{images.map((image, index) => (
<Image
key={index}
src={image}
alt={`Image ${index + 1}`}
style={{
width: '100px',
height: '100px',
objectFit: 'cover', //保持圖片比例並填充整個容器
opacity: index === currentImageIndex ? 1 : 0,
transition: 'opacity 0.5s ease-in-out',
//使用opacity屬性實現漸變效果,添加漸變效果的過渡動畫
}}
/>
))}
</div>
<button onClick={handlePrevImage}>Previous</button>
<button onClick={handleNextImage}>Next</button>
</div>
);
}
export default ImageSlider;
-
實作